<?php
/**
 * admin service file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/10/26
 * Time: 09:59
 */

namespace Modules\Shop\Service;

use HiCommon\Repository\ExpressRepository;
use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\StoreOrderRepository;
use HiCommon\Repository\StoreOrderRefundRepository;
use HiCommon\Service\PayService;

class StoreOrderService
{
    /**
     * 获取所有权限
     * @return array
     */
    public function get_all()
    {
        try {
            $arr_option = ['order' => ['key' => 'id', 'value' => 'asc']];
            $data = StoreOrderRepository::get_all($arr_option)->toarray();
            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 筛选条件处理
     * @param array $arr_search
     * @return mixed
     */
    public function search_handle($arr_search = [])
    {
        //$where['shop_id'] = shop_shop_id();//门店id
        $where['shop_id'] = $arr_search['shop_id'];//门店id
        if (!empty($arr_search['order_type'])) {
            $where['order_type'] = $arr_search['order_type'];
        }

        if (!empty($arr_search['order_no'])) {
            $where['order_no'] = $arr_search['order_no'];
        }

        if (!empty($arr_search['range'])) {
            $where['range'] = $arr_search['range'];
        }

        if (!empty($arr_search['status'])) {
            $where['status'] = $arr_search['status'];
            if ($arr_search['status'] == 100) {
                $where['status'] = 1;
                $where['pay_status'] = 1;
            } elseif ($arr_search['status'] == 200) {
                $where['status'] = 1;
                $where['pay_status'] = 2;
            } elseif ($arr_search['status'] == 300) {
                $where['status'] = 7;
            } elseif ($arr_search['status'] == 400) {
                $where['status'] = 9;
            }
        }

        return $where;
    }

    /**
     * 获取分页数据
     * @param $arr_search
     * @return array
     */
    public function get_list($arr_search)
    {
        try {
            //筛选条件
            $where = self::search_handle($arr_search);

            $arr_option['where'] = $where;
            $arr_option['with'] = ['getOrderGoods', 'order_refund'];
            $data = StoreOrderRepository::get_list($arr_option);
            $data->appends($arr_search);//添加链接参数
            $data = list_page_data($data, $arr_search);
            foreach ($data['data'] as $key => &$value) {
                $state = '';
                if (count($value['order_refund']) == 1) {
                    $state = ' - ' . StoreOrderRefundRepository::apply_state($value['order_refund'][0]['apply_state']);
                }

                $value['order_status'] = StoreOrderRepository::order_status($value['status'], $value['pay_status']) . $state;
            }
            $shop_id = $where['shop_id'];
            $data['d_num'] = StoreOrderRepository::get_count_by_where(['status' => 1, 'pay_status' => 2, 'shop_id' => $shop_id]);//待发货订单数量
            //$data['t_num'] = StoreOrderRepository::get_count_by_where(['status' => 6, 'pay_status' => 2, 'shop_id' => $shop_id]);//申请退款订单数量
            //$data['r_num'] = StoreOrderRepository::get_count_by_where(['status' => 8, 'pay_status' => 2, 'shop_id' => $shop_id]);//申请退货订单数量

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 查询一条数据
     * @param int $n_id
     * @return array
     */
    public function get_one(int $n_id)
    {
        try {
            $n_id = (int)$n_id;
            if ($n_id <= 0) {
                hello_error('数据ID不能为空');
            }

            //查询
            $arr_option['with'] = ['getUser', 'getOrderGoods', 'getAddress', 'getExpress', 'order_refund', 'get_cancel_reason', 'goods_comment'];
            $res = StoreOrderRepository::get_one($n_id, $arr_option)->toarray();
            $res['xpress'] = ExpressRepository::get_all()->toArray();//快递公司列表
            $res['order_state'] = StoreOrderRepository::order_status($res['status'], $res['pay_status']);
            $res['goods_comment'] = self::comment_data($res['goods_comment']);

            $res['order_refund_state'] = '';
            if (count($res['order_refund']) == 1) {
                $res['order_refund_state'] = StoreOrderRefundRepository::apply_state($res['order_refund'][0]['apply_state']);
            }

            if (empty($res)) {
                return hello_error('查询失败');
            }

            return hello_success('查询成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 评论数据处理
     * @param array $data
     * @return array
     */
    public function comment_data($data = [])
    {
        $result = [];
        if ($data) {
            foreach ($data as $key => &$value) {
                /* foreach (explode(',',$value['images']) as $item){
                     $value['images_arr'][] =  oss_full_url($item);
                 }*/
                $value['images'] = explode(',', $value['images']);
                $result[$value['goods_id']] = $value;
            }
        }

        return $result;
    }

    /**
     * 删除一条数据
     * @param $n_id
     * @return array
     */
    public function delete_one($n_id)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = StoreOrderRepository::delete_one($n_id);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 快速发货
     * @param $arr_input
     * @return array
     */
    public function sendGoods($arr_input)
    {
        try {
            $n_id = (int)$arr_input['id'];
            if ($n_id <= 0) {
                return hello_error('订单id不能为空');
            }
            $map = ['id' => $n_id];
            $up_data = [
                'xpress_id' => (int)$arr_input['xpress_id'],
                'delivery_no' => $arr_input['delivery_no'],
                'delivery_time' => date('Y-m-d H:i:s'),
                'status' => 2
            ];

            $res = StoreOrderRepository::edit_one($map, $up_data);

            if ($res === false) {
                return hello_error('操作失败');
            }

            //消息推送
            $express = ExpressRepository::get_one($arr_input['xpress_id'], ['field' => 'name'])->toArray();
            $dataNotice = [
                'notice_type' => 'ptshp_order_message_push',
                'order_id' => $n_id,
                'type' => 30,
                'title' => '商品发货通知',
                'content' => '已通过' . $express['name'] . '发货。'
            ];
            predis_notice_queue_in($dataNotice);

            return hello_success('操作成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取订单列表（导出Excel）
     * @param $arr_search
     * @return array
     */
    public function get_order_list($arr_search)
    {
        try {
            $arr_option['where'] = self::search_handle($arr_search);
            $arr_option['with'] = ['getUser', 'getOrderGoods', 'getAddress', 'getExpress', 'order_refund'];
            $data = StoreOrderRepository::get_all($arr_option)->toArray();
            foreach ($data as $key => &$value) {
                $value['order_status'] = StoreOrderRepository::order_status($value['status'], $value['pay_status']);
            }

            return $data;
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 修改单个字段
     * @param $arr_input
     * @return array
     */
    public function changStatus($arr_input)
    {
        try {
            if ($arr_input['id'] <= 0) {
                return hello_error('数据id不能为空');
            }
            $order_id = (int)$arr_input['id'];
            $status = (int)$arr_input['status'];
            $user_coupon_id = (int)$arr_input['user_coupon_id'];

            if ($status == 2) { //修改订单为已支付
                $up_data = [
                    'pay_status' => 2,
                    'pay_time' => date('Y-m-d H:i:s'),
                    'outer_trade_no' => 'hou-tai-zhi-fu'
                ];
                StoreOrderRepository::edit_one((array)['id' => $order_id], (array)$up_data);

                return hello_success('支付成功');
            }

            if ($status == 5) { //取消订单并回收库存
                $up_data = [
                    'status' => 5,
                    'order_status' => 5,
                    'cancel_time' => date('Y-m-d H:i:s', time()),
                    'cancel_reason_id' => 0
                ];
                StoreOrderRepository::edit_one(['id' => $order_id], $up_data);//取消订单

                StoreOrderRepository::cancelOrderBackStock((int)$order_id, $user_coupon_id);//回收库存

                //消息通知
                $dataNotice = [
                    'notice_type' => 'ptshp_order_message_push',
                    'order_id' => $order_id,
                    'type' => 37,
                    'title' => '取消订单通知',
                    'content' => '已被商家取消。'
                ];
                predis_notice_queue_in($dataNotice);

                return hello_success('取消成功');

            } else {
                return hello_error('所传状态有误');
            }

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 根据 订单id 订单编号 处理订单推送消息；
     * @param array $data
     * @return array
     */
    public function get_push_message($data = [])
    {
        $arr_option['with'] = ['getOrderGoods'];
        $arr_option['field'] = ['id', 'user_id', 'shop_id', 'status', 'pay_amount'];

        if (!empty($data['order_id'])) {
            $where = ['id' => $data['order_id']];
        } elseif (!empty($data['order_no'])) {
            $where = ['order_no' => $data['order_no']];
        } else {
            return hello_error('条件错误！');
        }
        $result = StoreOrderRepository::get_one_by_where($where, $arr_option);
        if ($result->first()) {
            $info = $result->toarray();

            $goods = array_shift($info['get_order_goods']);
            $goods_img = $goods['goods_pic']['full_src'];
            $goods_name = '您购买的【' . $goods['goods_name'];

            if (strlen($goods_name) > 40) {
                $goods_name = mb_substr($goods_name, 0, 20) . '...';
            }

            //消息推送
            $message = [
                'img' => $goods_img,              //图片地址  string
                'title' => $data['title'],        //标题  string
                'content' => $goods_name . '】' . $data['content'],    //内容  string
                'user_id' => $info['user_id'],    //用户id   int
                'pid' => 3,                       //消息类型  1：系统消息  2：活动消息  3：订单消息  int
                'order_id' => $info['id'],        //订单id  int
                'j_extend' => ['pid' => 3],       //极光推送的扩展字段  array
                'm_extend' => [                   //消息列表扩展字段    array
                    'is_refund_mes' => 1,
                    'order_type' => 1,
                    'type' => $data['type'],
                    'price' => $info['pay_amount'],
                    'order_status' => $info['status'],
                    'updated_at' => date('Y-m-d H:i:s')
                ]
            ];
            push_message($message);
            return hello_success('成功');
        }

        return hello_error('订单不存在！');
    }

}